<template>
    <div class="chatontag_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search2" @reset="reset2" />
        <ZwTable
            ref="sopTableRef"
            class="table-box page_table"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button v-auth="'CREAT_RULE'" type="primary" @click="ruleCreate">创建规则</el-button>
            </template>
        </ZwTable>
        <ZWDepart ref="DepartRef" @submit="getDepart"></ZWDepart>
        <!-- 客户明细抽屉 -->
        <ZWDrawer ref="DetailedRef" @close="close">
            <div class="drawer">
                <ZwSearchForm row-num="3" :option="searchOption1" @search.self="searchparam" @reset.self="reset" />
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    :option="tableOption1"
                    :fetch-params="state1.searchParams1"
                    :fetch-api="fetch()">
                </ZwTable>
            </div>
        </ZWDrawer>
        <Dialog :app-dialog="appDialog">
            <div class="dialog_content">{{ content }}</div>
        </Dialog>
    </div>
</template>

<script setup lang="tsx">
import { ref, reactive, computed, onMounted } from 'vue';

import { store } from '@/store';
import router from '@/router';
import ZWDepart from '@/components/ZWDepart.vue';
import Dialog from '@/components/Dialog.vue';
import ZWDrawer from '@/components/ZWDrawer.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { getSetionId, AFold, tableH, reSize } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { ElButton, ElMessage, ElPopover, ElTag } from 'element-plus';

import { getList, changeStatus, delList, detailList } from '@/api/customer/tag/chatontag';
import { getCreateList } from '@/api/common';
import womenlogo from '@/assets/customer/womenlogo.png';
import manlogo from '@/assets/customer/manlogo.png';

const search = reactive({ title: '', create_uids: [], create_time: '' });
const createTime = ref([]);
const page = reactive({ page: 1, page_size: 15, total: 0 });
const visible = ref(true);
const tabH = ref('500px');
const sopTableRef = ref();

// 表格的自适应高度
const getTableH = () => {
    tabH.value = tableH('.table-box');
};
const pickUp = () => {
    visible.value = !visible.value;
    AFold(visible.value, '.el_filter_row');
    getTableH();
};
const defaultParams = reactive({
    title: '',
    create_uids: [],
    create_time: []
});
const defaultParams1 = {};
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const state1 = reactive({
    searchParams1: deepCopy(defaultParams1)
});
const searchOption1 = computed(() => {
    return [
        {
            label: '关键词',
            name: 'key_word',
            value: '',
            type: 'select',
            placeholder: '请选择关键词',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve(keyword.value);
                });
            },
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '生效员工',
            name: 'effective_employee_ids',
            value: [],
            type: 'select',
            placeholder: '请选择生效员工',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            params: { department_id: '', is_wx_follow_user: 1, is_open_session_archive: -1 },
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '打标时间',
            name: 'label_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '客户姓名',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入客户姓名'
        },
        {
            label: '客户手机',
            name: 'mobile',
            value: '',
            type: 'input',
            placeholder: '请输入客户手机'
        }
    ];
});
const tableOption1 = [
    {
        prop: 'title',
        label: '客户信息',
        render({ row }) {
            return (
                <div class="chatontag_container_table_cell_common">
                    <img
                        src={row.avatar || 'https://img-scrm-dev.keyid.cn/keyid-scrm-server/avatar/cust_default.png'}
                        class="img"
                    />
                    <div class="right" style="display: flex">
                        <span style="font-size: 14px">{row.name} </span>
                        <div class="chatontag_container_table_cell_common">
                            <spans style="font-size: 12px; margin-right: 8px">{row.mobile || '手机号暂无'}</spans>
                            <img v-show={row.sex == 2} src={womenlogo} />
                            <img v-show={row.sex == 1} src={manlogo} />
                        </div>
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'effective_employee_name',
        label: '生效员工',
        width: 200,
        showOverflowTooltip: true
    },
    {
        prop: 'hit_keyword',
        label: '命中关键词',
        width: 120
    },
    {
        label: '打标时间',
        prop: 'created_at',
        width: 200
    }
];

const searchOption = computed(() => {
    return [
        {
            label: '规则名称',
            name: 'title',
            value: '',
            type: 'input',
            placeholder: '请输入规则名称搜索'
        },
        {
            label: '创建人',
            name: 'create_uids',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});

const tableOption = [
    {
        prop: 'title',
        label: '规则名称',
        width: 240
    },
    {
        prop: 'select_label',
        label: '自动打标签',
        minWidth: 220,
        isTag: true
    },
    {
        prop: 'state',
        label: '有效期',
        width: 320,
        render({ row }) {
            return (
                <>
                    <span vShow={row.validity_type == 1}>永久有效</span>
                    <div vShow={row.validity_type != 1}>
                        <div>{row.start_time}</div>
                        <span>至</span>
                        <div>{row.end_time}</div>
                    </div>
                </>
            );
        }
    },
    {
        prop: 'accurate_match',
        label: '设置关键词',
        minWidth: 250,
        render({ row }) {
            const slotReference = () => (
                <div class="clamp">
                    <span>精准匹配：</span>
                    {row.accurate_match.map((item: any) => {
                        return <ElTag>{item}</ElTag>;
                    })}
                </div>
            );
            const slotDefault = () => (
                <div class="clamp">
                    {row.accurate_match.map((item: any) => {
                        return <ElTag>{item}</ElTag>;
                    })}
                </div>
            );
            const slotReference2 = () => (
                <div class="clamp">
                    <span>精准匹配：</span>
                    {row.fuzzy_match.map((item: any) => {
                        return <ElTag>{item}</ElTag>;
                    })}
                </div>
            );
            const slotDefault2 = () => (
                <div class="clamp">
                    {row.fuzzy_match.map((item: any) => {
                        return <ElTag>{item}</ElTag>;
                    })}
                </div>
            );
            return (
                <>
                    <div v-show={row.fuzzy_match.length}>
                        <ElPopover
                            popper-class="popGroup auto_width zw-el-tags"
                            trigger="hover"
                            vSlots={{ reference: slotReference2, default: slotDefault2 }}
                            width={300}
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    </div>
                    <div v-show={row.accurate_match.length}>
                        <ElPopover
                            popper-class="popGroup auto_width zw-el-tags"
                            trigger="hover"
                            vSlots={{ reference: slotReference, default: slotDefault }}
                            width={300}
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    </div>
                </>
            );
        }
    },
    {
        label: '生效员工',
        prop: 'effective_employee',
        width: 140,
        render({ row }) {
            return (
                <div vShow={row.effective_employee.length > 0}>
                    <span>
                        {row.effective_employee.length == 1
                            ? row.effective_employee[0].name
                            : '员工' + row.effective_employee[0].name + '等' + row.effective_employee.length + '人'}
                    </span>
                </div>
            );
        }
    },
    {
        label: '状态',
        prop: 'status',
        width: 120,
        render({ row }) {
            return <span>{row.status_name}</span>;
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180
    },
    {
        prop: 'updated_at',
        label: '最近修改时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        width: 290,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '编辑',
                authCode: 'EDIT',
                click: (row: any) => router.push('/customer/tag/chatontag/editrule?id=' + row.id)
            },
            {
                name: '开启',
                authCode: 'CHANGE_STATUS',
                click: (row: any) => handleClick(1, row.id),
                isRender: ({ row }: any) => row.status == 2
            },
            {
                name: '暂停',
                authCode: 'CHANGE_STATUS',
                click: (row: any) => handleClick(2, row.id),
                isRender: ({ row }: any) => row.status == 1 || row.status == 4 || row.status == 3
            },
            { name: '删除', authCode: 'DEL', click: (row: any) => handleClick(3, row.id) },
            { name: '客户明细', authCode: 'GUEST_DETAIL', click: (row: any) => detail(row) }
        ]
    }
];
const search2 = (data: any) => {
    state.searchParams = deepCopy(data);
};
const reset2 = (v: any) => {
    state.searchParams = deepCopy(defaultParams);
};

//查询
const searchparam = v => {
    state1.searchParams1 = v;
};
const reset = v => {
    state1.searchParams1 = deepCopy(defaultParams1);
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getList;
};
const getids = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(detail_search.cust_chat_tag_id);
        }, 1);
    });
};
const fetch = async () => {
    const cust_chat_tag_id = await getids();
    return [{ cust_chat_tag_id }, detailList];
};
const statusList = reactive({
    cust_chat_tag_id: '', //标签规则主键ID
    status: '' //1 开始 2 暂停
});
const keyword = ref([]);
const content = ref('');
const tableData = ref([
    {
        id: '', //聊天标签规则ID
        title: '', //标题搜索
        select_label: [], //需要打的标签
        validity_type: 1, //1 长久有效 2 自定义时间段
        start_time: '', //2022-03-15 16:28:28
        end_time: '', //2022-03-15 16:28:28
        effective_employee: [], //选中的员工
        accurate_match: [], //精准匹配
        fuzzy_match: [], //模糊匹配  模糊匹配 与
        status: '', //1 开始 2 暂停 3进行中 4 未开始 5 结束
        created_at: '', //创建时间
        updated_at: '' //修改时间
    },
    {
        id: 6, //聊天标签规则ID
        tenant_id: 1, //商户ID
        zw_corp_id: 1, //企业ID
        title: '1212', //标题搜索
        select_label: [], //需要打的标签
        validity_type: '', //1 长久有效 2 自定义时间段
        start_time: '', //2022-03-15 16:28:28
        effective_employee: [], //选中的员工
        accurate_match: [], //精准匹配
        fuzzy_match: [], //模糊匹配  模糊匹配 与
        status: '', ////1 开始 2 暂停 3进行中 4 未开始 5 结束
        created_at: '', //创建时间
        updated_at: '' //修改时间
    }
]);
const detail_search = reactive({
    cust_chat_tag_id: ''
});
const detail_data = ref([
    {
        id: '', //聊天标签规则ID
        tenant_id: '', //商户ID
        zw_corp_id: '', //企业ID
        name: '', //客户名称
        mobile: '', //手机号码
        avatar: '', //客户头像
        effective_employee_name: '', //生效员工名称
        created_at: '', //打标时间时间
        hit_keyword: '' //命中的关键词
    }
]);
const time = ref('');
const creators = ref([]);
const DepartRef = ref(null);
const paginationRef = ref(null);
const pagination = ref(null);
const pageinit = ref(null);
const DetailedRef = ref(null);
const detailmember = ref([]);
const whichopen = ref(1); //判断是详情页的打开员工组件还是列表页打开员工组件，1是列表页
const cancelnew = () => {
    appDialog.visible = false;
};
const submitnew = () => {
    if (statusList.status == 3) {
        delList({ cust_chat_tag_id: statusList.cust_chat_tag_id }).then((res: any) => {
            const message = '删除成功';
            ElMessage({ message: message, type: 'success' });
            sopTableRef.value.reload();
        });
    } else {
        changeStatus(statusList).then((res: any) => {
            const message = statusList.status == 1 ? '开启成功' : '暂停成功';
            ElMessage({ message: message, type: 'success' });
            sopTableRef.value.reload();
        });
    }
    appDialog.visible = false;
};
const appDialog = reactive({
    visible: false,
    title: '删除提醒',
    content: '确定删除吗？',
    width: '400px',
    cancel: cancelnew,
    submit: submitnew,
    cancelText: '取消',
    submitText: '确定'
});
//打开员工弹窗
const opendept = (data: any, num: any) => {
    DepartRef.value.limit = num;
    whichopen.value = num;
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = num == 1 ? [...creators.value] : [...detailmember.value];
};
const getDepart = (res: any) => {
    if (whichopen.value == 1) {
        creators.value = res;
        search.create_uids = getSetionId('id', creators.value);
    } else {
        detailmember.value = res;
        detail_search.effective_employee_ids = getSetionId('id', detailmember.value);
    }
};
//删除选择的创建人
const changedept = (res: any) => {
    if (whichopen.value == 1) {
        creators.value = creators.value.filter((data: any) => res.includes(data.id));
        search.create_uids = getSetionId('id', creators.value);
    } else {
        detailmember.value = detailmember.value.filter((data: any) => res.includes(data.id));
        detail_search.effective_employee_ids = getSetionId('id', detailmember.value);
    }
};

//获取表格列表
const getpageList = (data?: any) => {
    if (createTime.value.length) {
        search.create_time = createTime.value.join('~');
    }
    const param = { ...search, page: data.page, page_size: data.page_size };
    getList(param).then((res: any) => {
        tableData.value = res.data;
        page.total = res.total;
        store.dispatch('pageTotal', res.total);
    });
};
//清空
const del = () => {
    search.title = '';
    search.create_uids = [];
    search.create_time = '';
    createTime.value = [];
    // DepartRef.value.removeItem(creators.value)
    creators.value = [];
    initpage();
};
//查询
const query = () => {
    initpage();
};
const getPagination = (res: any) => {
    page.page = res.page;
    page.page_size = res.page_size;
    page.total = res.total;
    initpage();
};
//创建规则弹窗
const ruleCreate = () => {
    router.push('/customer/tag/chatontag/createrule');
};
const handleClick = (data: any, id: any) => {
    appDialog.title = data == 1 ? '开启提醒' : data == 2 ? '暂停提醒' : '删除提醒';
    content.value = data == 1 ? '确定开启吗？' : data == 2 ? '确定暂停吗？' : '确定删除吗？';
    appDialog.visible = true;
    statusList.status = data;
    statusList.cust_chat_tag_id = id;
};
// 客户明细弹窗
const detail = async (data: any) => {
    detail_search.cust_chat_tag_id = data.id;
    keyword.value = [...data.fuzzy_match, ...data.accurate_match];
    const param = [];
    keyword.value.forEach(item => {
        const data = { name: '', id: '' };
        data.name = item;
        data.id = item;
        param.push(data);
    });
    keyword.value = param;
    DetailedRef.value.title = `【${data.title}】客户明细`;
    DetailedRef.value.width = 1000;
    DetailedRef.value.drawer = true;
    DetailedRef.value.isShow = false;
};
const close = () => {
    store.dispatch('pageTotal', page.total);
};
// 页面刷新
const initpage = () => {
    getpageList(page);
};
onMounted(() => {
    getTableH();
    reSize(getTableH);
});
</script>

<style lang="scss" scoped>
.chatontag_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .page_table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

:deep(.chatontag_container_table_cell_common) {
    display: flex;
    align-items: center;

    .right {
        flex-direction: column;
    }

    .img {
        width: 36px;
        height: 36px;
        border-radius: 4px;
        margin-right: 10px;
    }
}

:deep(.clamp) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;

    .tag {
        .el-tag {
            margin: 0 5px 5px 0;
        }
    }
}

:deep .btn_item {
    margin: 3px !important;
}
</style>
